package auctionhausen

class Bid {

	Float amount
	Customer bidder
	Date dateCreated
	Date lastUpdated

	static final MINIMUM_BID_DIFFERENCE = 0.50F
	static belongsTo = [listing: Listing]

	static constraints = {
		amount(validator : { amount, bid ->
			if (bid.listing) {
				Float amountToBeat = bid.listing.startingPrice
				def mostRecentBid = Bid.findAllByListing(bid.listing, [max: 1, sort: 'dateCreated', order : 'desc'])
				if (!mostRecentBid.isEmpty() && ((mostRecentBid[0].amount + MINIMUM_BID_DIFFERENCE) > amountToBeat)) {

					amountToBeat = mostRecentBid[0].amount + MINIMUM_BID_DIFFERENCE
				}

				return amount >= amountToBeat
			} else {
				return false
			}
		})
	}
	
	static namedQueries = {
		recentBidsOnListing { forListing ->
			eq 'listing', forListing
			maxResults(10)
		}
  }
}
